﻿/*
Commerce by Onex – eCommerce software platform (www.ecommerce.byonex.com)
Copyright (C) 2008-2010 by Onex Group

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 
 */
using System;
using System.Data;
using System.Collections.Generic;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ShopModel;
using ShopBLL;
using System.Globalization;

/// <summary>
/// Moduł odpowiedzialny za przepisywanie adresów Url
/// </summary>
public class RewriteModule : IHttpModule
{
    const string LANGUAGES_LIST = "ActiveLAnguagesForRewriteModule";
    #region IHttpModule Members

    public void Dispose()
    {

    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(RewriteModule_BeginRequest);
        context.PreRequestHandlerExecute += new EventHandler(RewriteModule_PreRequestHandlerExecute);
    }

    #endregion

    private void RewriteModule_BeginRequest(object sender, EventArgs e)
    {
        if (CommonTools.GetInstallationStatus() != CommonTools.InstallationStatus.Installed)
            return;

        System.Collections.Generic.List<string[]> rewriteRules = new System.Collections.Generic.List<string[]>();

        List<Language> languages;
        if (HttpContext.Current.Application[LANGUAGES_LIST] == null)
        {
            languages = ReportsManager.Instance.GetAvailableLanguages(true);
            HttpContext.Current.Application[LANGUAGES_LIST] = languages;
        }
        else
        {
            languages = (List<Language>)HttpContext.Current.Application[LANGUAGES_LIST];
        }

        foreach (Language lang in languages)
        {
            CultureInfo cU = new CultureInfo(lang.Culture);

            rewriteRules.Add(new string[] { @"/(\d{1,4}),(\d{1,4}),(\d{1,2})," + ((string)(HttpContext.GetGlobalResourceObject("Language", "Category", cU))).ToLower() + @",([\w+]{1,255}).aspx", "~/ProductList.aspx", "CategoryId=$1&Page=$2&Sort=$3" });
            rewriteRules.Add(new string[] { @"/(\d{1,8})," + ((string)(HttpContext.GetGlobalResourceObject("Language", "Product", cU))).ToLower() + @",([\w+]{1,255}).aspx", "~/ProductDetail.aspx", "ProductId=$1" });

            rewriteRules.Add(new string[] { @"/(\d{1,4})," + ((string)(HttpContext.GetGlobalResourceObject("Language", "Category", cU))).ToLower() + @".aspx", "~/ProductList.aspx", "CategoryId=$1" });
            rewriteRules.Add(new string[] { @"/(\d{1,4}),(\d{1,4})," + ((string)(HttpContext.GetGlobalResourceObject("Language", "Category", cU))).ToLower() + @",([\w+]{1,60}).aspx", "~/ProductList.aspx", "CategoryId=$1&SortId=$2" });
            rewriteRules.Add(new string[] { @"/(\d{1,4}),(\d{1,4})," + ((string)(HttpContext.GetGlobalResourceObject("Language", "Category", cU))).ToLower() + @".aspx", "~/ProductList.aspx", "CategoryId=$1&Page=$2" });
            rewriteRules.Add(new string[] { @"/(\d{1,4}),(\d{1,4}),(\d{1,2})," + ((string)(HttpContext.GetGlobalResourceObject("Language", "Category", cU))).ToLower() + @".aspx", "~/ProductList.aspx", "CategoryId=$1&Page=$2&Sort=$3" });
            rewriteRules.Add(new string[] { @"/(\d{1,4}),(\d{1,4}),(\d{1,2}),(\d{1,4})," + ((string)(HttpContext.GetGlobalResourceObject("Language", "Category", cU))).ToLower() + @".aspx", "~/ProductList.aspx", "CategoryId=$1&Page=$2&Sort=$3&ProducerId=$4" });

            rewriteRules.Add(new string[] { @"/(\d{1,8})," + ((string)(HttpContext.GetGlobalResourceObject("Language", "Product", cU))).ToLower() + @".aspx", "~/ProductDetail.aspx", "ProductId=$1" });
            rewriteRules.Add(new string[] { @"/cms/default.aspx", "~/cms/default.aspx", "" });
            rewriteRules.Add(new string[] { @"/cms/vouchers.aspx", "~/cms/vouchers.aspx", "" });            
            rewriteRules.Add(new string[] { @"/install/default.aspx", "~/install/default.aspx", "" });


            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlAbout", cU))).ToLower() + @".aspx", "~/About.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlBasket", cU))).ToLower() + @".aspx", "~/Basket.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlCategoryMap", cU))).ToLower() + @".aspx", "~/CategoryMap.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlClientChangePassword", cU))).ToLower() + @".aspx", "~/ClientChangePassword.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlClientInfo", cU))).ToLower() + @".aspx", "~/ClientInfo.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlClientOrders", cU))).ToLower() + @".aspx", "~/ClientOrders.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlClientPassword", cU))).ToLower() + @".aspx", "~/ClientPassword.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlContact", cU))).ToLower() + @".aspx", "~/Contact.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlDefault", cU))).ToLower() + @".aspx", "~/default.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlDelivery", cU))).ToLower() + @".aspx", "~/Delivery.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlErrorPage", cU))).ToLower() + @".aspx", "~/ErrorPage.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlInstalments", cU))).ToLower() + @".aspx", "~/Instalments.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlLogin", cU))).ToLower() + @".aspx", "~/login.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlNewClient", cU))).ToLower() + @".aspx", "~/NewClient.aspx", "" });
            rewriteRules.Add(new string[] { @"/(\d{1,8})," + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlNews", cU))).ToLower() + @".aspx", "~/News.aspx", "NewsID=$1" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlOffer", cU))).ToLower() + @".aspx", "~/Offer.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlOrderConfirmation", cU))).ToLower() + @".aspx", "~/OrderConfirmation.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlOrderDetail", cU))).ToLower() + @".aspx", "~/OrderDetail.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlOrderResult", cU))).ToLower() + @".aspx", "~/OrderResult.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlPayment", cU))).ToLower() + @".aspx", "~/Payment.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlPriceChanges", cU))).ToLower() + @".aspx", "~/PriceChanges.aspx", "" });
            rewriteRules.Add(new string[] { @"/(\d{1,8})," + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlPrintProduct", cU))).ToLower() + @".aspx", "~/PrintProduct.aspx", "Id=$1" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlProductError", cU))).ToLower() + @".aspx", "~/ProductError.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlProductsComparer", cU))).ToLower() + @".aspx", "~/ProductsComparer.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlRegulations", cU))).ToLower() + @".aspx", "~/Regulations.aspx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlShipment", cU))).ToLower() + @".aspx", "~/Shipment.aspx", "" });
            rewriteRules.Add(new string[] { @"/(\d{1,8})," + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlWatchVideo", cU))).ToLower() + @".aspx", "~/WatchVideo.aspx", "VideoID=$1" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlNewsRSS", cU))).ToLower() + @".ashx", "~/NewsRSS.ashx", "" });
            rewriteRules.Add(new string[] { @"/" + ((string)(HttpContext.GetGlobalResourceObject("Language", "UrlVouchers", cU))).ToLower() + @".aspx", "~/Vouchers.aspx", "" });
        }

        string path = HttpContext.Current.Request.Path;
        int idx = path.LastIndexOf('/');
        if (idx != -1)
            path = path.Substring(idx);

        foreach (string[] rule in rewriteRules)
        {
            Regex mask = new Regex(rule[0], RegexOptions.IgnoreCase);
            if (mask.IsMatch(HttpContext.Current.Request.Path))
            {
                HttpContext.Current.Items.Add("OriginalUrl", HttpContext.Current.Request.RawUrl);
                HttpContext.Current.RewritePath(rule[1], string.Empty, mask.Replace(path, rule[2]) + (!String.IsNullOrEmpty(HttpContext.Current.Request.QueryString.ToString()) ? ((String.IsNullOrEmpty(rule[2])) ? "" : "&") + HttpContext.Current.Request.QueryString.ToString() : ""));
                break;
            }
        }
    }

    private void RewriteModule_PreRequestHandlerExecute(object sender, EventArgs e)
    {
        if (HttpContext.Current.CurrentHandler != null && HttpContext.Current.CurrentHandler is Page)
        {
            ((Page)HttpContext.Current.CurrentHandler).PreRenderComplete += new EventHandler(OrginalUrl);
        }
    }

    private void OrginalUrl(object sender, EventArgs e)
    {
        if (HttpContext.Current.Items.Contains("OriginalUrl"))
        {
            string path = (string)HttpContext.Current.Items["OriginalUrl"];
            if (path.IndexOf("?") == -1)
            {
                path += "?";
            }

            HttpContext.Current.RewritePath(path);
        }
    }
}
